<?php

namespace App\Services\User;

use App\Constants\CodeData;
use App\Dao\CommonSettingDao;
use App\Dao\UserDao;
use App\Exception\MessageException;
use App\Model\Anchor;
use App\Model\Gift;
use App\Model\IncomeExpense;
use App\Model\User;
use App\Model\UserDel;
use App\Model\UserDelLimit;
use App\Model\UserIdentity;
use App\Utils\MemcacheClient;
use App\Utils\MongoDBClient;
use Hyperf\Context\Context;
use Hyperf\DbConnection\Db;
use Throwable;

class AccountService
{

    /**
     * Note - 判断是否可以注销账号
     * DateTime 2024/7/18 14:26
     * User Admin
     * @param $imei
     * @return array
     */
    public function canCancelAccount($imei)
    {
        $userInfo = Context::get('user');
        $language = Context::get('language', 'en');
        $uid = $userInfo['id'];
        // 单设备可注销次数
        if (!empty($imei) && !str_contains($imei, '0000000')) {
            $can_close_num = CommonSettingDao::getValue('can_close_account_num');
            $close_num = UserDel::query()->where('imei', $imei)->count();

            if ($close_num >= $can_close_num) {
                throw new MessageException('该设备注销次数已达到次数限制，若您需继续注销则需联系客服', CodeData::NEED_TIPS, ['result' => 1], false);
            }
        }

        if ($language == 'zh-cn') {
            $desc = "<p>您好，由于您的账号有异常，暂不能注销账号！<br>异常原因：因您被举报或者冻结积分，正在等待处理结果，待处理完后注销功能可使用！</p>";
        } elseif ($language == 'zh-hk') {
            $desc = "<p>您好，由於您的帳號出現異常，暫時無法注銷帳號！<br>異常原因：由於您遭到舉報或積分凍結，目前正在等待處理結果，待處理完畢後，注銷功能即可使用！</p>";
        } else {
            $desc = "<p>Hello, due to abnormal activity on your account, you cannot deactivate it at this moment!</p><p>Reason: Your account has been reported or your points are frozen, pending review. Once the issue is resolved, you will be able to deactivate your account.</p>";
        }

        if ($userInfo['integrate_freeze_count'] > 0) {
            throw new MessageException($desc, CodeData::NEED_TIPS, ['result' => 0], false);
        }
        if ($userInfo['sex'] != 1) {
            $this->limitCancel($uid, $desc);
        }
        $this->notLimitCancel($uid, $desc);

        return formatData(array('result' => 0), 200, 200, "账号可以注销");

    }


    /**
     * Note - 男用户直接返回可以注销
     * DateTime 2024/7/18 14:07
     * User Admin
     * @param $uid
     * @param $desc
     */
    private function notLimitCancel($uid, $desc)
    {
        $where = [
            'user_id' => $uid,
            'check_result' => '0',
        ];
        $options = array(
            'projection' => array('_id' => 0),
            'limit' => 1,
            'skip' => 0,
            'sort' => array('ctime' => -1)
        );
        $result = MongoDBClient::getInstance()->find('tb_tipoff', $where, $options);

        if (!empty($result)) {
            throw new MessageException($desc, CodeData::NEED_TIPS, ['result' => 0]);
        }
    }

    /**
     * Note - 限制注销
     * DateTime 2024/7/18 14:20
     * User Admin
     * @param mixed $uid
     * @param string $language
     */
    private function limitCancel(mixed $uid, string $language)
    {
        if ($language == 'zh-cn') {
            $desc = "<p>您的账号已被限制注销，请联系客服解除！</p>";
        } elseif ($language == 'zh-hk') {
            $desc = "<p>您的帳戶已被限制註銷，請聯繫客服解除！</p>";
        } else {
            $desc = "<p>Your account has been restricted from deactivation. Please contact customer support for assistance！</p>";
        }

        $delLimit = UserDelLimit::query()->where('uid', $uid)->first();
        // 礼物收益超过70%限制注销
        $inco = IncomeExpense::query()
            ->selectRaw('sum(amount) income, sum(if(sub_type=3,amount,0))')
            ->where('uid', $uid)->where('type', 1)->where('amount_type', 2)->first();
        if (!empty($delLimit)) {
            if ($delLimit['status'] == 1) {

                throw new MessageException($desc, CodeData::NEED_TIPS, ['result' => 0], false);

            } elseif ($delLimit['uncoil_time'] + 3 * 86400 <= time()) {
                // 解除限制3天后礼物收益再次达到70%限制注销
                if (!empty($inco) && $inco['income'] != 0 && ($inco['gift_income'] / $inco['income']) >= 0.7) {
                    UserDelLimit::query()->where('id', $delLimit['id'])->update([
                        'status' => 1,
                        'income' => $inco['income'],
                        'gift_income' => $inco['gift_income'],
                        'times' => time(),
                        'uncoil_time' => 0,
                    ]);
                    throw new MessageException($desc, CodeData::NEED_TIPS, ['result' => 0], false);
                }
            }
        } else {
            if (!empty($inco) && $inco['income'] != 0 && ($inco['gift_income'] / $inco['income']) >= 0.7) {
                UserDelLimit::query()->insert([
                    'uid' => $uid,
                    'status' => 1,
                    'income' => $inco['income'],
                    'gift_income' => $inco['gift_income'],
                    'times' => time(),
                ]);
                throw new MessageException($desc, CodeData::NEED_TIPS, ['result' => 0], false);
            }
        }

    }


    /**
     * Note - 注销账号
     * DateTime 2024/7/18 14:39
     * User Admin
     * @param $imei
     * @return array
     */
    public function cancelAccount($imei)
    {
        $userInfo = Context::get('user');
        $uid = $userInfo['id'];
        if (str_contains($imei, '0000000')) {
            $imei = '';
        }
        try {
            Db::beginTransaction();
            if ($userInfo['sex'] == 1) {
                UserDel::query()->updateOrInsert(
                    ['uid' => $uid, 'status' => 1, 'delete_time' => time()],
                    ['delete_time' => time()]
                );
                Db::commit();
                return formatData(array('result' => 1), 200, 200, "账号已注销,7天后清除账号记录");
            }

            UserDel::query()->updateOrInsert(
                ['imei' => $imei, 'uid' => $uid, 'status' => 2, 'delete_time' => time()],
                ['delete_time' => time()]
            );
            User::query()->where('id', $uid)
                ->update(['isdel' => 1,
                    'session_id' => '',
                    'online' => 0,
                    'phone' => $userInfo['phone'] . '_del',
                    'wx_openid' => $userInfo['wx_openid'] . '_del'
                ]);

            // 注销账号修改实名认证信息
            UserIdentity::query()->where('uid', $uid)->update(['user_status' => 1]);
            Db::commit();

            MemcacheClient::getInstance()->delete('userInfo_' . $uid);
            return formatData(array('result' => 1), 200, 200, "操作成功");
        } catch (Throwable $e) {
            Db::rollBack();
            throw new MessageException('操作失败', CodeData::NEED_TIPS, ['result' => 0, 'msg' => $e->getMessage()]);
        }

    }


    /**
     * Note - 判断用户金币是否足够
     * DateTime 2024/7/18 15:46
     * User Admin
     * @param $uid
     * @param $type
     * @param $giftId
     * @param $userId
     * @return array
     */
    public function judgeGold($uid, $type, $giftId, $userId)
    {
        $userInfo = User::query()->select(['id', 'gift_count', 'sex'])->where('id', $uid)->first();
        if ($userInfo['sex'] == 2) {
            return formatData(array('result' => 1, 'msg' => array()));
        }
        $goldIcon = $userInfo['gift_count']; //用户金币
        switch ($type) {
            default:
            case 0:
                if ($goldIcon < 5) {
                    throw new MessageException('金币不足', CodeData::NEED_TIPS, ['result' => 0, 'msg' => array()]);
                }
                break;
            case 1:
                $gift = Gift::query()->select(['id', 'price'])->find($giftId);
                if (empty($gift)) {
                    throw new MessageException('礼物信息有误', CodeData::NEED_TIPS, ['result' => 0, 'msg' => array()]);
                }
                $gift_price = $gift['price'];
                if ($goldIcon < $gift_price) {
                    throw new MessageException('金币不足', CodeData::NEED_TIPS, ['result' => 0, 'msg' => array()]);
                }
                break;
            case 2:
                if ($goldIcon < 8) {
                    throw new MessageException('金币不足', CodeData::NEED_TIPS, ['result' => 0, 'msg' => array()]);
                }
                break;
            case 3:
                if ($goldIcon < 10) {
                    throw new MessageException('金币不足', CodeData::NEED_TIPS, ['result' => 0, 'msg' => array()]);
                }
                break;
            case 4:
                // $anchor = (new AnchorModel())->find("uid,video_price", "uid=?", [$userId]);
                $anchor = Anchor::query()->select(['uid', 'video_price'])->where('uid', $userId)->first();
                if (empty($anchor)) {
                    throw new MessageException('主播信息有误', CodeData::NEED_TIPS, ['result' => 0, 'msg' => array()]);
                }
                $video_price = $anchor['video_price'];
                if ($goldIcon < $video_price) {
                    throw new MessageException('金币不足', CodeData::NEED_TIPS, ['result' => 0, 'msg' => array()]);
                }
                break;
        }
        return formatData(array('result' => 1, 'msg' => array()));
    }


}